package com.jing.weibo.controller.ranking;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import weibo4j.model.Comment;
import weibo4j.model.CommentWapper;
import weibo4j.model.WeiboException;

import com.jing.system.comm.BaseController;
import com.jing.system.comm.contants.RankingCons;
import com.jing.system.comm.contants.SystemCons;
import com.jing.system.comm.contants.WeiboCons;
import com.jing.system.comm.enums.FansAttentionType;
import com.jing.system.comm.enums.GenderType;
import com.jing.system.comm.enums.RuleType;
import com.jing.system.model.Ranking;
import com.jing.system.utils.DateUtil;
import com.jing.system.utils.PointCurrencyUtil;
import com.jing.weibo.pojo.ranking.UserComment;
import com.jing.weibo.pojo.ranking.UserCommentFans;
import com.jing.weibo.pojo.user.Synchrolog;
import com.jing.weibo.pojo.user.UserInfo;
import com.jing.weibo.service.ranking.UserCommentFansService;
import com.jing.weibo.service.ranking.UserCommentService;
import com.jing.weibo.service.user.SynchrologService;
import com.jing.weibo.service.user.UserInfoService;
import com.jing.weibo.ws.sina.CommentsService;
import com.jing.weibo.ws.sina.TimelineService;

/**
 * 榜上有名的Controller
 * @author jing.yue
 * @version 2012/09/29 1.0.0
 */
@Controller
public class RankingController extends BaseController {

	private static final Logger logger = Logger.getLogger(RankingController.class);

	@Autowired
	private TimelineService timelineService;
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private CommentsService commentsService;
	@Autowired
	private SynchrologService synchrologService;
	@Autowired
	private UserCommentService userCommentService;
	@Autowired
	private UserCommentFansService userCommentFansService;

	/**
	 * 跳转到@评论最多粉丝页面[类型为@类型]
	 * @param request
	 * @return
	 */
	@RequestMapping("/toRankingAtcommentManager")
	public String toPbUserTypeSeatManager(HttpServletRequest request, ModelMap modelMap) {
		return "user/ranking/rankingatcomment_manager";
	}

	/**
	 * 根据用户名获取@评论最多粉丝信息
	 * @return
	 */
	@RequestMapping(value = "/ranking/json/findByAtCommentUserComment")
	@ResponseBody
	public ModelMap findByAtCommentUserComment(HttpServletRequest request, UserComment userComment) {
		String result = null;
		Map<String, Object> map = null;
		UserInfo userInfo = getSessionUser(request);
		try {
			//同步@的信息
			synchrologUserComment(request, userInfo, FansAttentionType.TYPE_RANKING_AT);

			userComment.setUsername(userInfo.getUsername());
			userComment.setType(1);
			map = userCommentService.findByAtOrCommentUserComment(userComment);
			result = SUCCESS;
		} catch (Exception e) {
			logger.error(userInfo.getNickname() + ": 根据用户名获取@评论最多粉丝信息异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", map);
		modelMap.put("result", result);
		return modelMap;
	}

	/**
	 * 跳转到评论最多粉丝页面[类型为转发]
	 * @param request
	 * @return
	 */
	@RequestMapping("/toRankingCommentManager")
	public String toRankingCommentManager(HttpServletRequest request, ModelMap modelMap) {
		return "user/ranking/rankingcomment_manager";
	}

	/**
	 * 根据用户名获取评论最多粉丝信息
	 * @return
	 */
	@RequestMapping(value = "/ranking/json/findByCommentUserComment")
	@ResponseBody
	public ModelMap findByCommentUserComment(HttpServletRequest request, UserComment userComment) {
		String result = null;
		Map<String, Object> map = null;
		UserInfo userInfo = getSessionUser(request);
		try {
			//同步评论的信息
			synchrologUserComment(request, userInfo, FansAttentionType.TYPE_RANKING_COMMENT);

			userComment.setUsername(userInfo.getUsername());
			userComment.setType(0);
			map = userCommentService.findByAtOrCommentUserComment(userComment);
			result = SUCCESS;
		} catch (Exception e) {
			logger.error(userInfo.getNickname() + ": 根据用户名获取评论最多粉丝信息异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", map);
		modelMap.put("result", result);
		return modelMap;
	}

	/**
	 * 跳转到资深粉丝页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/toRankingSeniorManager")
	public String toRankingSeniorManager(HttpServletRequest request, ModelMap modelMap) {
		return "user/ranking/rankingsenior_manager";
	}

	/**
	 * 根据用户名获取资深粉丝信息
	 * @return
	 */
	@RequestMapping(value = "/ranking/json/findBySeniorUserComment")
	@ResponseBody
	public ModelMap findBySeniorUserComment(HttpServletRequest request, UserComment userComment) {
		String result = null;
		Map<String, Object> map = null;
		UserInfo userInfo = getSessionUser(request);
		try {
			//同步@的信息
			synchrologUserComment(request, userInfo, FansAttentionType.TYPE_RANKING_AT);
			//同步评论的信息
			synchrologUserComment(request, userInfo, FansAttentionType.TYPE_RANKING_COMMENT);

			userComment.setUsername(userInfo.getUsername());
			map = userCommentService.findByAtOrCommentUserComment(userComment);
			result = SUCCESS;
		} catch (Exception e) {
			logger.error(userInfo.getNickname() + ": 根据用户名获取资深粉丝信息异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", map);
		modelMap.put("result", result);
		return modelMap;
	}

	/**
	 * 根据类型/名次获取图片类型信息
	 * @return
	 */
	@RequestMapping(value = "/ranking/json/findByTypeRanking")
	@ResponseBody
	public ModelMap findByTypeRanking(HttpServletRequest request, String type, Integer grade) {
		List<Ranking> rankings = null;
		//为@评论
		if(RankingCons.ATCOMMENT.equals(type)) {
			switch (grade) {
			case 1:
				rankings = RankingCons.atcommentFirsts;
				break;
			default:
				rankings = RankingCons.atcommentOthers;
				break;
			}
		}
		//为评论
		else if(RankingCons.COMMENT.equals(type)) {
			switch (grade) {
			case 1:
				rankings = RankingCons.commentFirsts;
				break;
			default:
				rankings = RankingCons.commentOthers;
				break;
			}
		}
		//为资深
		else if(RankingCons.SENIOR.equals(type)) {
			switch (grade) {
			case 1:
				rankings = RankingCons.seniorFirsts;
				break;
			default:
				rankings = RankingCons.seniorOthers;
				break;
			}
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", rankings);
		return modelMap;
	}

	/**
	 * 根据[类型/名次/名次图片编号]保存奖励信息
	 * @return
	 */
	@RequestMapping(value = "/ranking/json/saveRanking")
	@ResponseBody
	public ModelMap saveRanking(HttpServletRequest request, String type, Integer grade, Integer gradeImgNo, String receiveUser) {
		String result = null;
		StringBuffer errorWeiboMsg = new StringBuffer();
		UserInfo userInfo = getSessionUser(request);
		//获取图片对象
		Ranking ranking = RankingCons.rankingMaps.get(type + "_" + grade + "_" + gradeImgNo);
		//处理妞币是否足够
		if(userInfo.getCurrency().intValue() < ranking.getCurrency().intValue()) {
			result = "currency_is_null";
		}
		else {
			String status = SystemCons.getRankingContent(type, userInfo.getUsername(), receiveUser);
			try {
				StringBuffer imgUrl = new StringBuffer(SystemCons.ABSOLUTE_PATH);
				imgUrl.append(File.separator).append(ranking.getImg());
				timelineService.updateStatus(status, imgUrl.toString(), userInfo.getToken());

				//颁奖一次
				PointCurrencyUtil pointCurrencyUtil = new PointCurrencyUtil(RuleType.TYPE_RANKING_SEND_WEIBO, userInfo.getUsername(), ranking.getCurrency());
				pointCurrencyUtil.handlePointCurrency();
				//同步Session中的用户信息
				setSessionUser(request, userInfoService.findByUserName(userInfo.getUsername()));
				result = SUCCESS;
			} catch (WeiboException e) {
				logger.error(WeiboCons.getErrorMsg(e));
				result = ERROR_WEIBO;
				errorWeiboMsg.append("调用微博接口出现异常[").append(WeiboCons.getErrorMsg(e)).append("]!");
			} catch (Exception e) {
				result = ERROR;
				logger.error(userInfo.getNickname() + ": 处理奖励信息异常!", e);
			}
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("result", result);
		modelMap.put("currency", userInfo.getCurrency());
		modelMap.put("errorWeiboMsg", errorWeiboMsg.toString());
		return modelMap;
	}

	/**
	 * 同步用户评论
	 * @param request
	 * @param userInfo
	 * @param fansAttentionType
	 * @throws WeiboException, Exception
	 */
	private void synchrologUserComment(HttpServletRequest request, UserInfo userInfo, FansAttentionType fansAttentionType) throws WeiboException, Exception {
		//判断是否同步过
		Synchrolog synchrolog = new Synchrolog();
		synchrolog.setUsername(userInfo.getUsername());
		synchrolog.setSynchrotable(fansAttentionType.getCode());
		Synchrolog sl = synchrologService.findByUserNameSynchrotable(synchrolog);

		Date querytime = DateUtils.addMinutes(DateUtil.getTime(), WeiboCons.UPDATE_PAST_DUE_DATE);
		//超过时间则从新获取数据[默认为25分钟]
		if(sl != null && sl.getSynchrotime().compareTo(querytime) != -1) {
			return;
		}
		Integer page = (sl != null && !"0".equals(sl.getNextcursor()) ? Integer.parseInt(sl.getNextcursor()) : 1);
		CommentWapper commentWapper = null;
		boolean bool = true;
		int num = 0;
		while(bool) {
			switch (fansAttentionType) {
			case TYPE_RANKING_AT:
				commentWapper = commentsService.getCommentMentions(page, WeiboCons.WEIBO_USER_PAGE_SIZE, userInfo.getToken());
				bool = handleCommentInfo(commentWapper, userInfo, 1);
				break;
			case TYPE_RANKING_COMMENT:
				commentWapper = commentsService.getCommentToMe(page, WeiboCons.WEIBO_USER_PAGE_SIZE, userInfo.getToken());
				bool = handleCommentInfo(commentWapper, userInfo, 0);
				break;
			}
			if(!bool) {
				page = 1;
				break;
			}
			page ++;
			//循环获取超过指定的次数
			if(num >= WeiboCons.WEIBO_USER_COMMENT_PAGE_NUM) {
				break;
			}
			num ++;
		}

		//不存在记录
		if(sl == null) {
			//添加用户同步记录
			synchrolog.setNextcursor(page.toString());
			synchrologService.saveSynchrolog(synchrolog);
		}
		//有数据
		else if(sl != null) {
			//根据用户名和同步的表名修改用户同步记录信息
			sl.setNextcursor(page.toString());
			synchrologService.updateSynchrolog(sl);
		}
	}

	/**
	 * 处理评论信息
	 * @param commentWapper
	 * @param userInfo
	 * @param type			类型[0评论/1@]
	 * @return				[true: 有数据/false: 没有数据]
	 * @throws Exception
	 */
	private Boolean handleCommentInfo(CommentWapper commentWapper, UserInfo userInfo, Integer type) throws Exception {
		if(commentWapper == null || commentWapper.getComments() == null || commentWapper.getComments().size() == 0) {
			return false;
		}
		List<Comment> comments = commentWapper.getComments();
		UserComment userComment = null;
		UserCommentFans userCommentFans = null;
		int num = 0;
		for (Comment comment : comments) {
			userComment = new UserComment();
			userComment.setCommentid(String.valueOf(comment.getId()));
			userComment.setUsername(userInfo.getUsername());
			userComment.setType(type);
			//处理是否存在相同的信息
			UserComment uc = userCommentService.findByUserComment(userComment);
			if(uc != null) {
				//连续出现WeiboCons.WEIBO_USER_COMMENT_PAGE_NUM * 5条存在的则跳出循环
				if(num > (WeiboCons.WEIBO_USER_COMMENT_PAGE_NUM * 5) ) {
					return false;
				}
				num ++;
				continue;
			}
			num = 0;

			userComment.setContent(comment.getText());
			userComment.setSource(comment.getSource());
			userComment.setCommentusername(comment.getUser().getId());
			userComment.setCweiboid(comment.getStatus().getId());
			userComment.setCweibocontent(comment.getStatus().getText());
			userComment.setCweibotime(comment.getStatus().getCreatedAt());
			userCommentService.saveUserComment(userComment);

			//处理微博用户
			userCommentFans = new UserCommentFans();
			userCommentFans.setUsername(comment.getUser().getId());
			userCommentFans.setNickname(comment.getUser().getScreenName());
			userCommentFans.setImg(comment.getUser().getavatarLarge());
			userCommentFans.setGender(GenderType.getCodeByText(comment.getUser().getGender()));
			userCommentFans.setAttentionnum(Integer.toString(comment.getUser().getFriendsCount()));
			userCommentFans.setFansnum(Integer.toString(comment.getUser().getFollowersCount()));
			userCommentFans.setWeibonum(Integer.toString(comment.getUser().getStatusesCount()));

			//保存信息
			if(userCommentFansService.findByUsernameUcf(userComment.getCommentusername()) == null) {
				userCommentFansService.saveUserCommentFans(userCommentFans);
			}
			//根据用户名修改信息
			else {
				userCommentFansService.updateUserCommentFans(userCommentFans);
			}
		}
		return true;
	}
}